package com.xuyoupeng.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.xuyoupeng.springframework.beans.BeansException;
import com.xuyoupeng.springframework.beans.factory.DisposableBean;
import com.xuyoupeng.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @author xuyoupneg
 * @description TODO
 * @date 2024/3/23 14:05
 */
public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;
    private final String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter (Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }
    @Override
    public void destroy() throws Exception {
        //实现销毁接口（DisposableBean）
        if (bean instanceof DisposableBean) {
           ((DisposableBean) bean).destroy();
        }
        //配置信息destroy-method(判断是为了避免二次销毁)
        if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new BeansException("Could not find a destroy method named " + destroyMethodName + " on bean with name " + beanName);
            }
            destroyMethod.invoke(bean);
        }
    }
}
